package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.db.AnalysisByDay;
import com.tanhua.domain.db.Log;
import com.tanhua.dubbo.api.db.LogApi;
import com.tanhua.dubbo.mapper.AnalysisByDayMapper;
import com.tanhua.dubbo.mapper.LogMapper;
import com.tanhua.dubbo.mapper.AnalysisByDayMapper;
import com.tanhua.dubbo.mapper.LogMapper;
import org.apache.dubbo.config.annotation.Service;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class LogApiImpl implements LogApi {

    @Autowired
    private LogMapper logMapper;
    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Override
    public void save(Log log) {
        logMapper.insert(log);
    }

    @Override
    public void analysis(String todayStr) {
        AnalysisByDay analysisByDay = new AnalysisByDay();

//        记录时间
        analysisByDay.setRecordDate(new DateTime(todayStr).toDate());

//        登录人数
//        select count( DISTINCT user_id )  num from tb_log   where log_time='2021-01-19' and  type='0101'
        Integer numLogin =  logMapper.queryNumLoginOrRegistry(todayStr,"0101");
        analysisByDay.setNumLogin(numLogin); //
//       注册人数
//        select count( DISTINCT user_id )  num from tb_log   where log_time='2021-01-19' and  type='0102'
        Integer numRegistry =  logMapper.queryNumLoginOrRegistry(todayStr,"0102");
        analysisByDay.setNumRegistered(numRegistry);

//       活跃人数
        Integer numActive =  logMapper.queryNumActive(todayStr);
        analysisByDay.setNumActive(numActive);

//       次日留存人数 minusDays是用来减天数的
        String yesTodayStr = new DateTime(todayStr).minusDays(1).toString("yyyy-MM-dd");
        Integer numRetention1d =  logMapper.queryRetention1d (todayStr,yesTodayStr);
        analysisByDay.setNumRetention1d(numRetention1d);



//        先根据时间查询AnalysisByDay数据，如果有就是更新 如果没有就是新增
        QueryWrapper<AnalysisByDay> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AnalysisByDay::getRecordDate,analysisByDay.getRecordDate());
        AnalysisByDay analysisByDay_db = analysisByDayMapper.selectOne(queryWrapper);

        if(analysisByDay_db==null){
            analysisByDayMapper.insert(analysisByDay);
        }else{
            analysisByDay.setId(analysisByDay_db.getId());
            analysisByDayMapper.updateById(analysisByDay);
        }
    }
}
